<template>
  <div class="my-upload">
    <h3>+</h3>
    <img alt="" v-if="imgUrl" :src="imgUrl" />
    <input type="file" @change="getFile" />
  </div>
</template>


<script>
import path from "path";
import { errorAlert } from "../utils/alert";
export default {
  data() {
    return {
        imgUrl:"",
    };
  },
  methods: {
    //点击上传图片按钮触发
    getFile(e) {
      let file = e.target.files[0] ? e.target.files[0] : {};
      console.log(e.target.files[0]);
      let extname = path.extname(file.name);
      console.log(extname);

      let arr = [".jpg", ".png", ".gif"];
      //判断文件类型
      if (!arr.includes(extname)) {
        errorAlert("你上传正确的文件");
        return;
      }
      //判断文件大小
      if (file.size >= 2 * 1024 * 1024) {
        errorAlert("文件大小不超过2M");
        return;
      }

     this.$emit('sendFile',file)

      //生成预览图
      this.imgUrl = URL.createObjectURL(file);
    },
     setImgUrl(url) {
      this.imgUrl = url;
    },
  },
};
</script>

<style scoped lang="less">
@import "../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  position: relative;
  h3 {
    text-align: center;
    line-height: 100px;
  }
  input,
  img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
  input {
    opacity: 0;
    background-color: transparent;
  }
}
</style>